import Cookies from 'js-cookie'
import axios from 'axios'

const TokenKey = 'kexio-token'
const RefreshTokenKey = 'kexio-refresh-token'

// Token过期时间（天）
const TOKEN_EXPIRE_DAYS = 7

// 获取访问令牌
export function getToken(): string | null {
  return Cookies.get(TokenKey) || localStorage.getItem(TokenKey) || null
}

// 设置访问令牌
export function setToken(token: string): void {
  // 同时保存到Cookie和localStorage，Cookie用于SSR，localStorage作为备份
  Cookies.set(TokenKey, token, { expires: TOKEN_EXPIRE_DAYS })
  localStorage.setItem(TokenKey, token)
  
  // 🔧 立即更新axios默认Authorization header
  updateAxiosAuthHeader(token)
}

// 移除访问令牌
export function removeToken(): void {
  Cookies.remove(TokenKey)
  localStorage.removeItem(TokenKey)
  localStorage.removeItem(RefreshTokenKey)
  
  // 🔧 立即清除axios默认Authorization header
  clearAxiosAuthHeader()
}

// 获取刷新令牌
export function getRefreshToken(): string | null {
  return localStorage.getItem(RefreshTokenKey) || null
}

// 设置刷新令牌
export function setRefreshToken(refreshToken: string): void {
  localStorage.setItem(RefreshTokenKey, refreshToken)
}

// 移除刷新令牌
export function removeRefreshToken(): void {
  localStorage.removeItem(RefreshTokenKey)
}

// 检查是否已登录
export function isLoggedIn(): boolean {
  const token = getToken()
  return !!token
}

// 解析JWT Token
export function parseJWT(token: string): any {
  try {
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    )
    return JSON.parse(jsonPayload)
  } catch (error) {
    console.error('JWT解析失败:', error)
    return null
  }
}

// 检查Token是否过期
export function isTokenExpired(token: string): boolean {
  try {
    const payload = parseJWT(token)
    if (!payload || !payload.exp) {
      return true
    }
    
    const currentTime = Math.floor(Date.now() / 1000)
    return payload.exp < currentTime
  } catch {
    return true
  }
}

// 获取Token过期时间
export function getTokenExpireTime(token: string): Date | null {
  try {
    const payload = parseJWT(token)
    if (!payload || !payload.exp) {
      return null
    }
    return new Date(payload.exp * 1000)
  } catch {
    return null
  }
}

// 检查Token是否即将过期
export function isTokenExpiringSoon(token: string, thresholdMinutes: number = 10): boolean {
  try {
    const payload = parseJWT(token)
    if (!payload || !payload.exp) {
      return true
    }
    
    const currentTime = Math.floor(Date.now() / 1000)
    const thresholdSeconds = thresholdMinutes * 60
    
    return (payload.exp - currentTime) <= thresholdSeconds
  } catch {
    return true
  }
}

// 从Token中获取用户信息
export function getUserInfoFromToken(token: string): any {
  try {
    const payload = parseJWT(token)
    if (!payload) {
      return null
    }
    
    return {
      userId: payload.userId || payload.sub,
      username: payload.username,
      tenantId: payload.tenantId,
      roles: payload.roles || [],
      permissions: payload.permissions || []
    }
  } catch {
    return null
  }
}

// 清除所有认证相关数据
export function clearAuthData(): void {
  removeToken()
  removeRefreshToken()
  
  // 清除其他可能的认证相关数据
  localStorage.removeItem('kexio-user-store')
  localStorage.removeItem('kexio-permission-store')
  sessionStorage.removeItem('kexio-permission-store')
  
  // 🔧 确保清除axios认证header
  clearAxiosAuthHeader()
}

// 格式化Token显示（隐藏敏感信息）
export function formatTokenForDisplay(token: string): string {
  if (!token || token.length < 20) {
    return token
  }
  
  const start = token.substring(0, 8)
  const end = token.substring(token.length - 8)
  return `${start}...${end}`
}

// 🔧 立即更新axios默认Authorization header
export function updateAxiosAuthHeader(token: string): void {
  if (token) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
    console.log(`🔑 Token已立即更新到axios: ${formatTokenForDisplay(token)}`)
  }
}

// 🔧 清除axios默认Authorization header
export function clearAxiosAuthHeader(): void {
  delete axios.defaults.headers.common['Authorization']
  console.log('🚫 Token已从axios中清除')
}
